import { IBezierTiming, IDefaultTiming } from "../index.d"

/**
 * 三阶贝塞尔曲线 可参考：https://segmentfault.com/a/1190000018597975
 * @param t 
 * @param a1 
 * @param a2 
 * @param a3 
 * @param a4 
 * @returns 
 */
function bezierCount(t: number, a1: number, a2: number, a3: number, a4: number) {
  return a1 * (1 - t) * (1 - t) * (1 - t) + 3 * a2 * t * (1 - t) * (1 - t) + 3 * a3 * t * t * (1 - t) + a4 * t * t * t;
}

export const count = (eventTiming: any, percent: number): number => {

  let ev = (eventTiming as IDefaultTiming);

  if (percent >= 1) {
    return ev.to;
  }
  if ( eventTiming.type !== undefined ) {
    // console.log('ease-out', bezierCount(percent, 0, 0, 0.58, 1), 'percent', percent);
    if ( ev.type === 'ease' ) return bezierCount(percent, 0.25, 0.1, 0.25, 1) * percent * (ev.to - ev.from) + ev.from;
    else if ( ev.type === 'linear' ) return bezierCount(percent, 0, 0, 1, 1) * percent * (ev.to - ev.from) + ev.from;
    else if ( ev.type === 'ease-in' ) return bezierCount(percent, .42, 0, 1, 1) * percent * (ev.to - ev.from) + ev.from;
    else if ( ev.type === 'ease-out' ) return bezierCount(percent, 0, 0, 0.58, 1) * percent * (ev.to - ev.from) + ev.from;
    else if ( ev.type === 'ease-in-out' ) return bezierCount(percent, .42, 0, .58, 1) * percent * (ev.to - ev.from) + ev.from;
    else return 0;
  } else {
    let ev = (eventTiming as IBezierTiming);
    return bezierCount(percent, ev.x1, ev.y1, ev.x2, ev.y2) * percent * (ev.to - ev.from) + ev.from;
  }
}


export const transformCount = (transformValue: string, changeName: string, newValue: string) => {
  const transformList = transformValue.match(/\w+?\([\w\.]+?\)/g) || [];
  let is = false;
  transformList.forEach((item, index) => {
    if (!is && item.includes(changeName)) {
      transformList[index] = `${changeName}(${newValue})`;
      is = true;
    }
  })
  !is && transformList.push(`${changeName}(${newValue})`);
  // console.log('transformCount', transformValue, 'new:', transformList.join(' '));

  return transformList.join(' ');
}

